use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

fn main() {
    test_parse().expect("parse fail");
    test_serialize().expect("serialize fail");
    test_json_value();
}

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: i32,
    phones: Vec<String>,
}

fn test_parse() -> Result<(), serde_json::Error> {
    let data: &str = r#"
        {
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }
    "#;

    let v: Value = serde_json::from_str(data)?;
    let p: Person = serde_json::from_str(data)?;

    println!("Please call {} at the number {}", v["name"], v["phones"][0]);
    println!("Please call {} at the number {}", p.name, p.phones[0]);

    Ok(())
}

fn test_serialize() -> Result<(), serde_json::Error> {
    let p = Person {
        name: "xiao_ming".to_owned(),
        age: 18,
        phones: vec!["123".to_string()],
    };

    println!("{}", serde_json::to_string(&p)?);
    Ok(())
}

fn test_json_value() {
    let v = json!({
        "name": "xiao_hua",
        "age": 1,
        "phones": [
            format!("+44 138")
        ]
    });
    println!("json: {}", v["name"]);
}
